package com.library.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.library.entity.Book;
import com.library.entity.UserVoteBook;
import com.library.service.IBookService;
import com.library.util.Options;
import com.library.util.Pagination;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by linzhi on 2016/12/12.
 */
@Service
@Transactional
public class BookService extends BaseService<Book> implements IBookService {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Override
    public JSONObject findBooksByPagination(Options options) {
        StringBuffer hql = new StringBuffer();
        List<Object> params = new LinkedList<>();
        JSONObject myPagination = new JSONObject();
        JSONArray myData = new JSONArray();

        //一、默认
        if (options.getListType() == null || options.getListType().equals(Options.OPTIONS_LISTTYPE_DEFAULT)) {
            /****************根据条件拼接hql********************/
            hql.append("from Book b where 1=1 ");
            //搜索条件
            if (!StringUtils.isEmpty(options.getSearchStr())) {
                hql.append("and (b.title like ? or b.author like ? or b.isbn like ?) ");
                params.add("%" + options.getSearchStr() + "%");
                params.add("%" + options.getSearchStr() + "%");
                params.add("%" + options.getSearchStr() + "%");
            }
            //谁荐购的书
            if (options.getUserId() != null) {
                hql.append("and b.user.id=? ");
                params.add(options.getUserId());
            }
            //书的状态
            if (options.getStatus() != null) {
                hql.append("and b.status=? ");
                params.add(options.getStatus());
            }
            //书的语言
            if (options.getLanguage() != null) {
                hql.append("and b.language=? ");
                params.add(options.getLanguage());
            }
            hql.append("order by b.createTime desc");
            Pagination<Book> pagination = bookDao.findPagination(hql.toString(), params.toArray(), options.getPageNo(), options.getPageSize());

            /****************封装Json********************/
            //封装data
            for (Book book : pagination.getData()) {
                JSONObject myBook = getJsonBook(book, options);
                myData.add(myBook);
            }
            myPagination.put("books", myData);
            //封装分页数据
            getJsonPage(myPagination, pagination);
        }
        //二、投票榜
        else if (options.getListType().equals(Options.OPTIONS_LISTTYPE_RANKING)) {
            Pagination<Book> pagination = bookDao.findPagination("from Book b where b.status=1 order by b.userVoteBooks.size desc,b.createTime desc", options.getPageNo(), options.getPageSize());

            /****************封装Json********************/
            //封装data
            for (Book book : pagination.getData()) {
                JSONObject myBook = getJsonBook(book, options);
                myData.add(myBook);
            }
            myPagination.put("books", myData);
            //封装分页数据
            getJsonPage(myPagination, pagination);
        }
        //三、某用户投票的荐书列表
        else if (options.getListType().equals(Options.OPTIONS_LISTTYPE_VOTE)) {
            /****************根据条件拼接hql********************/
            hql.append("from UserVoteBook v where 1=1 ");
            //谁投票的书
            if (options.getUserId() != null) {
                hql.append("and v.user.id=? ");
                params.add(options.getUserId());
            }
            //书的状态
            if (options.getStatus() != null) {
                hql.append("and v.book.status=? ");
                params.add(options.getStatus());
            }
            hql.append("order by v.createTime desc");
            Pagination<UserVoteBook> pagination = userVoteBookDao.findPagination(hql.toString(), params.toArray(), options.getPageNo(), options.getPageSize());

            /****************封装Json********************/
            //封装data
            for (UserVoteBook vote : pagination.getData()) {
                Book book = vote.getBook();
                JSONObject myBook = getJsonBook(book, options);
                myData.add(myBook);
            }
            myPagination.put("books", myData);
            //封装分页数据
            getJsonPage(myPagination, pagination);
        }
        return myPagination;
    }

    @Override
    public void addBookStatus(Book book) {
        Book book1 = bookDao.get(book.getId());
        if (book1.getStatus() < 3) {
            book1.setStatus(book1.getStatus() + 1);
        }
    }

    @Override
    public void reduceBookStatus(Book book) {
        Book book1 = bookDao.get(book.getId());
        if (book1.getStatus() > 1) {
            book1.setStatus(book1.getStatus() - 1);
        }
    }

    //封装分页数据
    private void getJsonPage(JSONObject myPagination, Pagination pagination) {
        myPagination.put("pageNo", pagination.getPage());
        myPagination.put("pageSize", pagination.getRows());
        myPagination.put("nextPage", pagination.getNextPage());
        myPagination.put("prePage", pagination.getPrePage());
        myPagination.put("pageCount", pagination.getPageCount());
        myPagination.put("totalCount", pagination.getCount());
    }

    //封装单个Book为JsonObject
    private JSONObject getJsonBook(Book book, Options options) {
        JSONObject myBook = new JSONObject();
        myBook.put("id", book.getId());
        myBook.put("title", book.getTitle());
        myBook.put("author", book.getAuthor());
        myBook.put("publisher", book.getPublisher());
        myBook.put("pubdate", book.getPubdate());
        myBook.put("isbn", book.getIsbn());
        myBook.put("image", book.getImage());
        myBook.put("url", book.getUrl());
        myBook.put("voteCount", book.getUserVoteBooks().size());
        myBook.put("createTime", sdf.format(book.getCreateTime()));
        myBook.put("status", book.getStatus());
        //后台才用到的属性
        myBook.put("language", book.getLanguage());
        myBook.put("reason", book.getReason());
        //当前登录用户是否投票过
        for (UserVoteBook userVoteBook : book.getUserVoteBooks()) {
            if (userVoteBook.getUser().getId().equals(options.getLoginUserId())) {
                myBook.put("isVote", true);
                break;
            }
        }
        return myBook;
    }

}
